﻿var express = require("express");
var app = express();
var session = require("express-session");
var bodyParser = require('body-parser')
var db = require('./db.js')
const crypto = require('crypto');
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

app.use(session({
    secret: '1',
    resave: true,
    saveUninitialized: true
}));


//注册
app.post("/users/registr", function (req, res) {
    var md5 = crypto.createHash('md5');
    req.body.Pw = md5.update(req.body.Pw).digest('base64')
    // req.body.Pw = md5.update(req.body['Pw']).digest('base64');  //加密后的值

    db.insertDocuments('user',req.body, function (err, result) {
        if (err) {
            res.send(err)
        }
        else {
            console.log(req.body);
            req.session.login = "1";//1代表这个人是注册成功的
            req.session.username = req.body.user;
            req.session.sid = req.body.id;

            res.json({"result": 1});
        }
    })


    // console.log(sql);
});
//登录
app.post("/users/login", function (req, res) {

    db.findDocuments('user', {id: req.body.id}, function (err, result) {
        if (err)
            console.log(err);
        var md5 = crypto.createHash('md5');
        var originPw = md5.update(req.body.Pw).digest('base64')
        if (result.length == 0) {
            res.json({"result": 0});
            return
        }
        if (result[0].Pw == originPw) {
            var user = result[0].user
            var id = result[0].id
            req.session.username = user;
            req.session.sid = id;
            req.session.login = "1";

            res.json({"result": 1,'user':user,'sid':id});

        } else {
            res.json({"result": 2});
        }
    })
});
app.post("/users/user", sess);
function sess(req, res, next) {
    if (req.session.login == "1") {
        //console.log('进来了显示页面');
        var username = req.session.username;
        var login = req.session.login;
        var sid = req.session.sid;
        res.send({"result": 1,'username': username, 'sid': sid});
    } else {
        res.json({"result": 0});
    }
};
//注销
app.post("/users/logout",function (req,res) {
    req.session.login = "0";
    res.json({"result": 1});
    //console.log(req.session);


});


app.listen(3000);